package br.com.amigooo.controller;


import static br.com.caelum.vraptor.view.Results.json;

import java.util.ArrayList;
import java.util.List;

import br.com.amigooo.Session.UserSession;
import br.com.amigooo.model.AccessRequest;
import br.com.amigooo.model.Item;
import br.com.amigooo.model.Order;
import br.com.amigooo.model.PanelOrder;
import br.com.amigooo.model.ReturnMessage;
import br.com.amigooo.model.User;
import br.com.amigooo.repository.AccessRequestImpl;
import br.com.amigooo.repository.ItemImpl;
import br.com.amigooo.repository.OrderImpl;
import br.com.amigooo.repository.UserImpl;
import br.com.amigooo.util.Utils;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class PanelController {

	private Result result;
    private UserSession userSession;
    private ReturnMessage returnMessage;
	
    public PanelController(Result result, UserSession userSession) {
        this.result = result;
        this.userSession = userSession;
    }
    
	@Path("/panel")
	public void main() {
		List<AccessRequest> accessList = getUserRequest();
		List<AccessRequest> activeList = getActiveUsers();
		List<PanelOrder> orderList = getOrders();

		if(accessList != null && accessList.size() == 0){
			result.include("access", null);
		}else{
			result.include("access", accessList);
		}

		if(activeList != null && activeList.size() == 0){
			result.include("active", null);
		}else{
			result.include("active", activeList);
		}

		if(orderList != null && orderList.size() == 0){
			result.include("orders", null);
		}else{
			result.include("orders", orderList);
		}

	}

	/**
	 * Busca os pedidos de acesso para a empresa
	 * @return Lista de acessos
	 */
	private List<AccessRequest> getUserRequest(){
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		List<AccessRequest> accessList = null;
		
		try{
			accessList = accessRequestImpl.getAccessByCompany(
				this.userSession.getUser().getEstablishment().getId());
		}catch(RuntimeException e){
			e.printStackTrace();
			
			return null;
		}
		
		return accessList;
	}
	
	/**
	 * Busca os usuarios ativos
	 * @return Lista de usuarios ativos
	 */
	private List<AccessRequest> getActiveUsers(){
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		List<AccessRequest> accessRequestList = null;
		
		try{
			accessRequestList = accessRequestImpl.getActiveAccessByCompany(
					this.userSession.getUser().getEstablishment().getId());
		}catch(RuntimeException e){
			e.printStackTrace();
			
			return null;
		}
		
		return accessRequestList;
	}
	
	/**
	 * Busca os pedidos ativos
	 * @return Lista de pedidos
	 */
	private List<PanelOrder> getOrders(){
		OrderImpl orderImpl = new OrderImpl();
		ItemImpl itemImpl = new ItemImpl();
		
		PanelOrder panelOrder = null;
		List<Order> orderList = null;
		List<PanelOrder> listPanel = new ArrayList<PanelOrder>();
		
		try{
			orderList = orderImpl.getOrderByCompany(this.userSession.getUser().getEstablishment().getId());
			
			if(orderList != null && orderList.size() > 0){
				for (Order o : orderList){
					
					if(itemImpl.getItem(o.getItem()) != null){
						
						Item item = itemImpl.getItem(o.getItem());
						
						panelOrder = new PanelOrder();
						panelOrder.setItem(item);
						panelOrder.setUser(o.getUser());
						panelOrder.setOrder(o);
						
						listPanel.add(panelOrder);
					}
				}
			}
			
		}catch(RuntimeException e){
			e.printStackTrace();
			
			return null;
		}
		
		return listPanel;
	}
	
	@Path("/order/status")
	@Post
	public void changeOrderStatus(String id,String status){
		OrderImpl orderImpl = new OrderImpl();
		
		if(id != null){
			Order order = orderImpl.getOrder(Integer.parseInt(id));
			
			if(order != null){
				order.setStatus(Integer.parseInt(status));
				
				try{
					orderImpl.update(order);
					this.returnMessage = new ReturnMessage("Status alterado", null, "success");
					result.use(json()).from(this.returnMessage).serialize();
				}catch(Exception e){
					this.returnMessage = new ReturnMessage("Erro ao alterar o status do pedido", "error", null);
					result.use(json()).from(this.returnMessage).serialize();
				}
			}
		}
		
	}
	
	/**
	 * Busca informações do usuário
	 * @param item
	 */
	
	@Path("/user/{user.email}")
	@Get
	public void getUserInfo(User user){
		UserImpl userImpl = new UserImpl();
		try{
			User usr = userImpl.getUser(user.getEmail());

			if(usr != null && usr.getEmail() != null){
				AccessRequest accessRequest = new AccessRequest();
				AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
				
				accessRequest = accessRequestImpl.getAccessByUser(user.getEmail());
				result.use(json()).from(accessRequest).include("user").serialize();
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("erro", "Usuário não existe " + e.getMessage(), null);
			result.use(json()).from(this.returnMessage).serialize();
		}
	}
	
	@Path("/panel/confirmaccess/{id}")
	@Post
	public void confirmAccess(Integer id){
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		AccessRequest accessRequest = new AccessRequest();
		try{
			if(id != null){
				accessRequest = accessRequestImpl.getAccessRequest(id);
				
				if(accessRequest != null && accessRequest.getId() != null && accessRequest.getStatus() == 1){
					accessRequest.setStatus(0);
					accessRequestImpl.update(accessRequest);
					this.returnMessage = new ReturnMessage(accessRequest.getId().toString(), null, "Usuário liberado.");
				}else{
					this.returnMessage = new ReturnMessage("erro", "Usuário não está na lista, foi aceito ou cancelado.", null);
				}
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			result.include("error", Utils.message("Ocorreu um erro ao liberar o acesso.", Utils.ERROR));
			result.use(json()).from(this.returnMessage).serialize();
		}
		result.use(json()).from(this.returnMessage).serialize();
	}
	
	
	@Path("/panel/denyaccess/{id}")
	@Post
	public void denyAccess(Integer id){
		AccessRequest accessRequest = new AccessRequest();
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		try{
			if(id != null){
				accessRequest = accessRequestImpl.getAccessRequest(id);
				
				if(accessRequest != null && accessRequest.getId() != null && (accessRequest.getStatus() == 1 || accessRequest.getStatus() == 0)){
					accessRequest.setStatus(2);
					accessRequestImpl.update(accessRequest);
					
					this.returnMessage = new ReturnMessage(accessRequest.getId().toString(), null, "Usuário cancelado.");
				}else{
					this.returnMessage = new ReturnMessage("erro", "Usuário não está na lista, foi aceito ou cancelado.", null);
				}
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			result.include("error", Utils.message("Ocorreu um erro ao liberar o acesso.", Utils.ERROR));
			result.use(json()).from(this.returnMessage).serialize();
		}
		
		result.use(json()).from(this.returnMessage).serialize();
	}
	
	@Path("/mobile/accessorder")
	@Get
	public void getAccesOrder(String access){
		OrderImpl orderImpl = new OrderImpl();
		ItemImpl itemImpl = new ItemImpl();
		List<Item> itens = new ArrayList<Item>();
		
		try{
			if(access != null){
				List<Order> orders = orderImpl.getOrderByAccess(Integer.parseInt(access));
	
				if(orders != null && !orders.isEmpty()){
//					for(Order o : orders){
//						itens.add(itemImpl.getItem(o.getItem()));
//					}
					
					result.use(json()).from(orders).include("itemObj").serialize();
				}else{
					this.returnMessage = new ReturnMessage("Nenhum pedido", null, "success");
					result.use(json()).from(this.returnMessage).serialize();
				}
			}else{
				this.returnMessage = new ReturnMessage("Nenhum pedido", null, "success");
				result.use(json()).from(this.returnMessage).serialize();
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("erro", "Erro ao pesquisar por pedidos", null);
			result.use(json()).from(this.returnMessage).serialize();
		}
	}
}
